package com.sh.sales.happysales.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.sh.polymedicine.happysale.result.SimpleResult;
import com.sh.polymedicine.happysale.result.UserInfoResult;
import com.sh.polymedicine.happysale.service.envelop.HappySaleManager;
import com.sh.sales.happysales.R;
import com.sh.sales.happysales.app.AppData;
import com.sh.sales.happysales.app.utils.LoginOutUtil;
import com.sh.sales.happysales.app.utils.TimerUtil;
import com.sh.sales.happysales.base.BaseActivity;
import com.sh.sales.happysales.datautils.LocalUserInfoUtils;
import com.sh.sales.happysales.service.LoginObsever;
import com.sh.sales.happysales.view.NewToast;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;

/**
 * Created by zhouyucheng on 2017/9/14.
 */

public class BindPhoneActivity extends BaseActivity implements LoginObsever {
    private String TAG = "BindPhoneActivity";
    @BindView(R.id.btn_canclebind)
    TextView btnCanclebind;
    @BindView(R.id.happysale_logo)
    ImageView happysaleLogo;
    @BindView(R.id.phone_number)
    EditText phoneNumber;
    @BindView(R.id.btn_getcode)
    TextView btnGetcode;
    @BindView(R.id.phone_code)
    EditText phoneCode;
    @BindView(R.id.btn_bind_login)
    Button btnBindLogin;

    @BindView(R.id.bind_phnum)
    LinearLayout mView;


    TimerUtil timerUtil;
    private Context mContext;
    private UserInfoResult info;
    private PopupWindow popupWindow;
    private String phNum;
    private Subscriber<SimpleResult> mSimpleResultSub;
    private Subscriber<SimpleResult> mSimpleBindSub;

    private int refreshSignTag = -1;
    private String userSign;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_phone);
        mAppManager.addActivity(this);
        mContext = this;
        ButterKnife.bind(this);
        mLoginObserable.registerObserver(this);
        userSign = AppData.getInstence().getmUserToken().getUserSign();
        if (timerUtil == null) {
            timerUtil = TimerUtil.getInstance(mContext);
            timerUtil.setOnTimeListener(new TimerUtil.OnTimeListener() {
                @Override
                public void onTime(int time) {
                    if (btnGetcode != null) {
                        btnGetcode.setTextColor(getApplication().getResources().getColor(R.color.colorPrimary));
                        btnGetcode.setText(time + TimerUtil.MESSAGE_EXTRAL);
                        btnGetcode.setClickable(false);
                    } else {
                        Log.i(TAG, "onTime:btnGetcode is  null ");
                    }
                }

                @Override
                public void onEnd() {
                    btnGetcode.setText(mContext.getResources().getString(
                            R.string.phone_code));
                    btnGetcode.setTextColor(getApplication().getResources().getColor(R.color.bt_login));
                    btnGetcode.setClickable(true);
                }
            });
        }

    }

    @OnClick({R.id.btn_canclebind, R.id.btn_getcode, R.id.btn_bind_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_canclebind:
                mAppManager.finishActivity(this);
                break;
            case R.id.btn_getcode:
                getVerificationCode();
                break;
            case R.id.btn_bind_login:
                connectBindPhone();
                break;
        }
    }


    private void getVerificationCode() {
        phNum = phoneNumber.getText().toString().trim();
        if (!isMobileNO(phNum)) {
            NewToast.makeText(mContext, getResources().getString(R.string.canuse_phone));
            return;
        }
        refreshSignTag = 1;
        if (mSimpleResultSub != null) {
            if (!mSimpleResultSub.isUnsubscribed()) {
                mSimpleResultSub.unsubscribe();
            }
        }
        Log.i(TAG, "getVerificationCode: " + userSign);
        mSimpleResultSub = new Subscriber<SimpleResult>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())){
                    String message =e.getCause().getCause().getMessage();
                    NewToast.makeText(mContext, message);
                    int ret =Integer.valueOf( e.getCause().getMessage()) ;
                    if (ret>=100&&ret<200){
                        LoginOutUtil.logOut(BindPhoneActivity.this);
                    }
                }else if (HappySaleManager.DATA_NULL.equals(e.getMessage())){
                    NewToast.makeText(mContext, e.getCause().getMessage());
                }else{
                    NewToast.makeText(mContext, "获取短信验证码失败");
                }
            }

            @Override
            public void onNext(SimpleResult mSimpleResult) {
                NewToast.makeText(BindPhoneActivity.this, "验证码发送中...");
                timerUtil.startCountTime();
                btnGetcode.setClickable(false);
            }

        };
        mHappySaleManager.sendVerificationCode(phNum, userSign, mSimpleResultSub).subscribe(mSimpleResultSub);
    }

    private void connectBindPhone() {
        phNum = phoneNumber.getText().toString().trim();
        String code = phoneCode.getText().toString().trim();
        refreshSignTag = 2;
        if (mSimpleBindSub != null) {
            if (!mSimpleBindSub.isUnsubscribed()) {
                mSimpleBindSub.unsubscribe();
            }
        }
        mSimpleBindSub = new Subscriber<SimpleResult>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())){
                    String message =e.getCause().getCause().getMessage();
                    NewToast.makeText(BindPhoneActivity.this, message);
                    int ret =Integer.valueOf( e.getCause().getMessage()) ;
                    if (ret>=100&&ret<200){
                        LoginOutUtil.logOut(BindPhoneActivity.this);
                    }
                }else if (HappySaleManager.DATA_NULL.equals(e.getMessage())){
                    NewToast.makeText(mContext, e.getCause().getMessage());
                }else{
                    NewToast.makeText(mContext, "获取短信验证码失败");
                }
            //    finiBindPhnum();
            }

            @Override
            public void onNext(SimpleResult result) {
                UserInfoResult m = AppData.getInstence().getmUserInfoResult();
                m.setMobile(phNum);
                LocalUserInfoUtils.updataUserInfoResult(m, m.getInfoId());
                finiBindPhnum();
            }
        };
        mHappySaleManager.bindMobile(phNum, code, userSign, mSimpleBindSub).subscribe(mSimpleBindSub);
    }


    private void finiBindPhnum() {
        Intent mIntent = new Intent();
        mIntent.putExtra("phoneNum", phNum);
        mIntent.setClass(this, PerfectInfoActivity.class);
        startActivity(mIntent);
        finish();
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][358]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    @Override
    protected void onDestroy() {
        if (timerUtil != null) {
            timerUtil.StopTimer();
        }
        mLoginObserable.unregisterObserver(this);
        super.onDestroy();
    }

    @Override
    public void refreshUserSign(int Position) {
        userSign = AppData.getInstence().getmUserToken().getUserSign();
        switch (refreshSignTag) {
            case 1:
                getVerificationCode();
                break;
            case 2:
                connectBindPhone();
                break;
        }


    }
}
